import {
  home
} from '../../api/index'
import {
  formatTime
} from "../../utils/util";
let leftHeight = 0,
  rightHeight = 0; //分别定义左右两边的高度
let query;
const app = getApp()
Page({
  data: {
    bannerList: [],
    bannerActivityList: [],
    statusBarHeight: app.globalData.statusBarHeight,
    navHeightM: app.globalData.navHeightM,
    IMGBASEURL: app.globalData.IMGBASEURL,
    isFixed: false, //是否吸顶
    navTop: 0, //nav菜单距离顶部距离
    tabList: [],
    tagListOne: [{
        text: '推荐',
        val: 13
      }, {
        text: '关注',
        val: 100
      }, {
        text: '收藏',
        val: 101
      },
      // {
      //   text: '视频',
      //   val: 12
      // },
    ],
    tagListT: ['全部', '室内', '建筑', '景观', '其他'],
    tagActive: 13,
    tagActiveT: '全部',
    list: [],
    leftList: [],
    rightList: [],
    listLoadStatus: 0,
    pullDownRefreshing: false,
    isRenderOver: true,
    defaultValue: 0,
    isMengcheng: false,
    num: 0,
    navHeadH: 0,
    CommunityId: '',
    haibaoUrl: [],
    DataKey: 'CreationSeries'
  },
  listPagination: {
    index: 0,
    num: 10,
  },
  onShareAppMessage() {},
  goTop() {
    if (wx.pageScrollTo) {
      wx.pageScrollTo({
        scrollTop: 0
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }
  },
  shudLogin() {
    const popup = this.selectComponent('#popupid');
    popup.setData({
      visible: true
    })
  },
  goPage() {
    wx.switchTab({
      url: '/pages/ai/index',
    })
  },
  goPagepp() {
    wx.navigateTo({
      url: '/pages/home/test-page/index',
    })
  },
  chlichTap(e) {
    let _this = this
    if (!wx.getStorageSync("token")) {
      wx.showModal({
        content: "是否登录查看更多功能？",
        success(res) {
          if (res.confirm) {
            _this.shudLogin()
          }
        },
      });
      return;
    }
    const isOne = e.currentTarget.dataset['isone']
    const index = e.currentTarget.dataset['index']
    let obj = {}
    obj[isOne ? 'tagActive' : 'tagActiveT'] = index
    this.setData({
      ...obj
    })
    if (this.data.isFixed) {
      wx.pageScrollTo({
        scrollTop: this.data.navTop,
      })
      setTimeout(() => {
        this.loadData(true)
      }, 500)
    } else {
      this.loadData(true)
    }

  },
  onTabsChange(e) {
    wx.pageScrollTo({
      scrollTop: this.data.tabList[e.detail.val]?.Id == 'CreationSeries' ? 0 : this.data.navTop,
    })
    this.setData({
      defaultValue: e.detail.val,
      CommunityId: this.data.tabList[e.detail.val]?.Id,
      tagActive: 13,
      tagActiveT: '全部'
    })
    setTimeout(() => {
      this.loadData(true)
    }, 500)
  },
  goSearch() {
    wx.navigateTo({
      url: '/pages/home/search/index',
    })
  },
  onShow() {
    this.getTabBar().init();
    if (wx.getStorageSync('token')) {
      // this.showQian()
      home.newusergifttelepathyasync().then(res => {
        if (res.StatusCode == 200) {
          this.setData({
            num: res.Result.NewUserTelepathy,
            NewUserVipDays: res.Result.NewUserVipDays,
            haibaoUrl: res.Result.WindowList.map(e => ({
              url: e,
              isOpen: true
            })),
            isMengcheng: true
          })
        }
      })
    }
  },
  onHide() {
    const popup = this.selectComponent('#popupid');
    if (popup.data.visible) {
      popup.setData({
        visible: false
      })
    }

  },
  onPullDownRefresh() {
    if (this.data.listLoadStatus === 0 && this.data.isRenderOver) {
      this.loadData(true)
    } else {
      wx.stopPullDownRefresh()
    }
  },
  onReachBottom() {
    // this.data.defaultValue === 0
    if (this.data.listLoadStatus === 0 && this.data.isRenderOver) {
      this.loadData();
    }
  },
  async loadData(fresh = false) {
    this.setData({
      listLoadStatus: 1
    });
    const pageSize = this.listPagination.num;
    let pageIndex = this.listPagination.index + 1;
    if (fresh) {
      pageIndex = 1;
      this.setData({
        leftList: [],
        rightList: []
      })
    }
    try {
      let res = []
      let obj = {
        "PageIndex": pageIndex, //第几页
        "PageSize": pageSize, //每页数据量
        "CommunityId": this.data.CommunityId
      }
      if (this.data.CommunityId != 'CreationSeries') {
        if (this.data.tagActive === 100) {
          res = await home.getcontentbyfollow(obj)
        } else if (this.data.tagActive === 101) {
          res = await home.getmycollectionbypage(obj)
        } else {
          res = await home.getbypage({
            ...obj,
            "QueryType": this.data.tagActive, //查询类型（11同城，12视频，13推荐，14热点）
            "Category": this.data.tagActiveT === '全部' ? '' : this.data.tagActiveT, //分类，传空查全部
            "LoadingTime": formatTime(new Date(), 'YYYY-MM-DD')
          })
        }
      } else {
        res = await home.getseriespage({
          "ActivePort": 3,
          "PageIndex": 1,
          "PageSize": 10
        })
        this.data.isRenderOver = true
      }

      const nextList = res.Result.Datas
      this.setData({
        list: fresh ? nextList : this.data.list.concat(nextList),
      });
      this.setData({
        listLoadStatus: this.data.list.length == res.Result.TotalCount ? 2 : 0,
      });
      if (this.data.CommunityId != 'CreationSeries') {
        const {
          leftList,
          rightList
        } = this.data;
        query = wx.createSelectorQuery().in(this);
        for (let index = 0; index < nextList.length; index++) {
          if (index == 0) {
            this.data.isRenderOver = false
          }
          const item = nextList[index];
          if (this.data.listLoadStatus == 1) {
            this.data.isRenderOver = true
            return
          }
          if (this.data.leftList.length === 0 && this.data.rightList.length === 0) {
            leftList.push(item)
          } else {
            leftHeight <= rightHeight ? leftList.push(item) : rightList.push(item); //判断两边高度，来觉得添加到那边
          }
          await this.getBoxHeight(leftList, rightList);
          if (index == nextList.length - 1) {
            this.data.isRenderOver = true
          }
          if (fresh) {
            wx.stopPullDownRefresh();
          }
        }
      }
      this.listPagination.index = pageIndex;
      this.listPagination.num = pageSize;
    } catch (error) {
      this.setData({
        listLoadStatus: 3
      });
    }

  },
  onReTry() {
    this.loadData(true);
  },
  getBoxHeight(leftList, rightList) { //获取左右两边高度
    return new Promise((resolve, reject) => {
      this.setData({
        leftList,
        rightList
      }, () => {
        query.select('#left').boundingClientRect();
        query.select('#right').boundingClientRect();
        query.exec((res) => {
          setTimeout(() => {
            leftHeight = res[0].height; //获取左边列表的高度
            rightHeight = res[1].height; //获取右边列表的高度
            resolve();
          }, 0)
        });
      });
    })
  },
  bannerGo(e){
    let url= e.currentTarget.dataset.url
    console.log(url);
    wx.navigateTo({
      url,
    })
    
  },
  onReady() {
    // 获取节点距离顶部的距离
    wx.createSelectorQuery().select("#nav").boundingClientRect((rect) => {
      if (rect && rect.height) {
        this.setData({
          navTop: parseInt(rect.top)
        })
      }
    }).exec()
    wx.createSelectorQuery().select("#tabsId").boundingClientRect((rect) => {
      if (rect && rect.height) {
        this.setData({
          navHeadH: parseInt(rect.height)
        })
      }
    }).exec()
    home.getbannerinfolist({
      BannerInfoQueryParams: {
        BannerInfoGroupType: 'HomeBanner',
        ClientType: 3
      }
    }).then((res) => {
      if (res.StatusCode === 200) {
        this.setData({
          bannerList: res.Result
        })
      }
    })
    home.getbannerinfolist({
      BannerInfoQueryParams: {
        BannerInfoGroupType: 'CreationBanner',
        ClientType: 3
      }
    }).then((res) => {
      if (res.StatusCode === 200) {
        this.setData({
          bannerActivityList: res.Result
        })
      }
    })
    home.selectenabledlist({
      CommunityType: 3
    }).then((res) => {
      this.setData({
        CommunityId: res.Result[0]['DataKey'],
        tabList: res.Result.map((e, index) => ({
          text: e.Name,
          key: index,
          Id: e.DataKey
        }))
      })
      this.loadData();
    })
  },
  // showQian() {
  //   const tabs = this.selectComponent('#tabsId');
  //   if (app.globalData.userStatus.UserInfoStatus == 0) {
  //     tabs.setData({
  //       visible: true
  //     })
  //   }

  // },
  // 监听页面滚动事件
  onPageScroll(e) {
    let scrollTop = parseInt(e.scrollTop),
      isFixed = scrollTop >= this.data.navTop;
    if (this.data.isFixed !== isFixed) {
      this.setData({
        isFixed
      })
    }
    this.setData({
      bg: scrollTop >= 10
    })
  },
  onClose(e) {
    const index = e.currentTarget.dataset['index']
    let arr = this.data.haibaoUrl
    arr[index]['isOpen'] = false
    this.setData({
      haibaoUrl: arr
    })
    this.setData({
      isMengcheng: !arr.every(e => !e.isOpen)
    })
  }
})